<?php
//header('Content-Type: application/vnd.ms-excel;charset=utf-8');
header('Content-Type: text/html;charset=utf-8');
set_time_limit(0);
include_once dirname(dirname(dirname(__FILE__))) . "/nncms_manager_inc.php";
include_once LOGIC_DIR . '/nl_common.func.php';
include_once LOGIC_DIR . 'stock_import' . DIRECTORY_SEPARATOR . 'stock_import.class.php';
include_once $nncms_config_path . 'mgtv_v2' . DIRECTORY_SEPARATOR . 'mgtv_init.php';
include_once $nncms_config_path . 'mgtv_v2' . DIRECTORY_SEPARATOR . 'models' . DIRECTORY_SEPARATOR . 'queue_task_model.php';
include_once $nncms_config_path . 'v2' . DIRECTORY_SEPARATOR . 'common.php';

$dc = nl_get_dc(array (
		'db_policy' => NL_DB_READ | NL_DB_WRITE,
));
$dc->open();
$targetFolder = dirname(__FILE__);

//下载模板
if(isset($_GET['web_action']) && $_GET['web_action'] === 'download_csv')
{
    download_template_csv($targetFolder.'/import.zip');
}

$org_id = $_POST["nns_org_id"];
$org_type = $_POST["nns_org_type"];
$verifyToken = md5('unique_salt' . $_POST['timestamp']);

if(!isset($_POST['nns_cp_id']) || !isset($_POST['nns_type']))
{
	echo return_csv_msg(1,"<font color='red'>未选择来源与导入媒资类型</font><script>alert('未选择来源与导入媒资类型')</script>");
}
else 
{
	//根据CPID查询SPID
	$sp_info = array();
	$data = nl_sp::query_bind_cp_info($dc, $_POST['nns_cp_id']);
	if($data['ret'] == '0' && !empty($data['data_info']) && is_array($data['data_info']))
	{
		$sp_info = $data['data_info'];
	}
	if (!empty($_FILES) && $_POST['token'] == $verifyToken)
	{
	    try
	    {	    	
	    	$str_func = "stock_" . $_POST['nns_type'] . "_by_csv";
	    	echo $str_func($dc,$_FILES['Filedata']['tmp_name'],$_POST['nns_cp_id'],$_POST['nns_queue_name'],$sp_info);	    	
	    }
	    catch (Exception $e)
	    {
	        echo return_csv_msg(1,"<font color='red'>CSV文件格式错误</font><script>alert('CSV文件格式错误')</script>");
	    }
	}
}

function download_template_csv($file_path)
{
    $basename = basename($file_path);
    //打开文件
    $file = fopen ( $file_path, "r" );
    //输入文件标签
    Header ( "Content-type: application/octet-stream" );
    Header ( "Accept-Ranges: bytes" );
    Header ( "Accept-Length: " . filesize ( $file_path ) );
    Header ( "Content-Disposition: attachment; filename=" . $basename );
    echo fread ( $file, filesize ( $file_path ) );
    fclose ( $file );
    exit ();
}
/**
 * 主媒资从CSV导入
 * @param object $dc
 * @param string $upload_file 上传文件
 * @param string $source_id 上游来源信息
 * @param string $queue_name 导入队列名
 * @param array $sp_info 
 */
function stock_video_import_by_csv($dc,$upload_file,$source_id,$queue_name,$sp_info)
{
	$upload_file = fopen($upload_file, 'r');
	$num = 0;
	$first = false;
	$flag = true;
	//$queue_task_model = new queue_task_model();
	while (!feof($upload_file))
	{
		$line_arr = fgetcsv($upload_file);
		if($first === false)
		{
			unset($first);
			continue;
		}
		if (is_array($line_arr) && !empty($line_arr))
		{
			$relase_time = empty($line_arr[12]) ? date('Y-m-d',time()) : $line_arr[12];
			//整理vod
			$vod_info = array(
					'nns_asset_import_id' => $line_arr[0],
					'nns_name' => $line_arr[1],
					'nns_pinyin' => $line_arr[2],
					'nns_asset_category' => $line_arr[3],
					'nns_director' => $line_arr[4],
					'nns_actor' => $line_arr[5],
					'nns_kind' => $line_arr[6],
					'nns_keyword' => $line_arr[7],
					'nns_area' => $line_arr[8],
					'nns_all_index' => $line_arr[9],
					'nns_summary' => $line_arr[10],
					'nns_language' => $line_arr[11],
					'nns_show_time' => $relase_time,
					'nns_producer' => $line_arr[13],
					'nns_cp_id' => $source_id,
					'nns_state' => 2,//导入
					'nns_check' => 1,//已审核
			);
			$stock = nl_stock_import::stock_video_import($dc, $vod_info, $source_id);//导入媒资
			if($stock['ret'] != 0 || empty($queue_name) || empty($sp_info))
			{
				continue;
			}	
			//$stock返回的是主媒资GUID
			switch ($queue_name)
			{
				case 'core_import'://加入中心同步队列
					foreach ($sp_info as $sp)
					{
						//检查中心同步队列是否存在
						$check_params = array(
							'nns_type' => 'video',
							'nns_video_id' => $stock['data_info']['vod_id'],
							'nns_org_id' => $sp['nns_id'],
							'nns_cp_id' => $source_id
						);
						$check_op_queue = nl_op_queue::get_overtime_op_queue_by_condition($dc, $check_params);
						if($check_op_queue['ret'] != '0')
						{
							continue;
						}
						//$config = json_decode($sp['nns_config'],true);
						if(!is_array($check_op_queue['data_info']) || empty($check_op_queue['data_info']))//不存在则添加，存在则忽略
						{
							$op_add_params = array(
									'nns_type' => 'video',
									'nns_video_id' => $stock['data_info']['vod_id'],
									'nns_org_id' => $sp['nns_id'],
									'nns_cp_id' => $source_id,
									'nns_create_time' => date('Y-m-d H:i:s',time()),
									'nns_action' => 'add',
									'nns_status' => 0,
									'nns_name' => "[{$line_arr[1]}]",
									'nns_op_mtime' => round(np_millisecond_f()*1000),
									'nns_release_time' => $relase_time,
							);
							nl_op_queue::add($dc, $op_add_params);
							//$queue_task_model->q_add_task($stock['data_info'], 'video', 'add',$sp['nns_id'],null,false,'',null,0,'',$config);
						}
					}
					//
					break;
				case 'c2_import'://加入C2队列
					foreach ($sp_info as $sp)
					{
						//检查C2队列是否存在
						$check_c2 = nl_c2_task::query_c2_exsist($dc, 'video', $stock['data_info']['vod_id'], $sp['nns_id']);
						if($check_c2['ret'] != '0')
						{
							continue;
						}
						if(!is_array($check_c2['data_info']) || empty($check_c2['data_info']))//不存在则添加
						{
							$c2_add_params = array(
									'nns_type' => 'video',
									'nns_ref_id' => $stock['data_info']['vod_id'],
									'nns_org_id' => $sp['nns_id'],
									'nns_cp_id' => $source_id,
									'nns_create_time' => date('Y-m-d H:i:s',time()),
									'nns_action' => 'add',
									'nns_status' => 1,
									'nns_name' => "[{$line_arr[1]}]",
									'nns_all_index' => $line_arr[9],
							);
							nl_c2_task::add($dc, $c2_add_params);
						}
						else //存在则把状态置为初始状态 
						{
							$edit_params = array(
									'nns_action' => 'add',
									'nns_status' => 1,
									'nns_epg_status' => 97,
									'nns_all_index' => $line_arr[9],
                                    'nns_ref_id' => $stock['data_info']['vod_id'],
							);
							nl_c2_task::edit($dc, $edit_params, $check_c2['data_info'][0]['nns_id']);
						}
					}
					break;
			}
		}
	}
	fclose($upload_file);
}

/**
 * 分集从CSV导入
 * @param object $dc
 * @param string $upload_file 上传文件
 * @param string $source_id 上游来源信息
 * @param string $queue_name 导入队列名
 * @param array $sp_info
 */
function stock_index_import_by_csv($dc,$upload_file,$source_id,$queue_name,$sp_info)
{
	$upload_file = fopen($upload_file, 'r');
	$num = 0;
	$first = false;
	$flag = true;
	//$queue_task_model = new queue_task_model();
	while (!feof($upload_file))
	{
		$line_arr = fgetcsv($upload_file);
		if($first === false)
		{
			unset($first);
			continue;
		}
		if (is_array($line_arr) && !empty($line_arr))
		{
			$relase_time = empty($line_arr[8]) ? date('Y-m-d',time()) : $line_arr[8];
			$asset_import_id = $line_arr[0];//主媒资ID
			//整理vod_index
			$vod_index_info = array(
					'nns_import_id' => $line_arr[1],
					'nns_name' => $line_arr[2],
					'nns_time_len' => $line_arr[3],//导入单位为秒
					'nns_director' => $line_arr[4],
					'nns_actor' => $line_arr[5],
					'nns_index' => ($line_arr[6] - 1) > 0 ? $line_arr[6] - 1 : 0,
					'nns_summary' => $line_arr[7],
					'nns_release_time' => $relase_time,
					'nns_action' => 'add',
					'nns_cp_id' => $source_id,
			);
			$stock = nl_stock_import::stock_index_import($dc, $vod_index_info,$asset_import_id, $source_id);//导入媒资
			if($stock['ret'] != 0 || empty($queue_name) || empty($sp_info))
			{
				continue;
			}
			//$stock返回的是主媒资GUID+分集的GUID array('vod_id','vod_name','index_id')
			switch ($queue_name)
			{
				case 'core_import'://加入中心同步队列
					foreach ($sp_info as $sp)
					{
						//检查中心同步队列是否存在
						$check_params = array(
								'nns_type' => 'index',
								'nns_video_id' => $stock['data_info']['vod_id'],
								'nns_index_id' => $stock['data_info']['index_id'],
								'nns_org_id' => $sp['nns_id'],
								'nns_cp_id' => $source_id
						);
						$check_op_queue = nl_op_queue::get_overtime_op_queue_by_condition($dc, $check_params);
						if($check_op_queue['ret'] != '0')
						{
							continue;
						}
						//$config = json_decode($sp['nns_config'],true);
						if(!is_array($check_op_queue['data_info']) || empty($check_op_queue['data_info']))//不存在则添加，存在则忽略
						{
							$op_add_params = array(
									'nns_type' => 'index',
									'nns_video_id' => $stock['data_info']['vod_id'],
									'nns_index_id' => $stock['data_info']['index_id'],
									'nns_org_id' => $sp['nns_id'],
									'nns_cp_id' => $source_id,
									'nns_create_time' => date('Y-m-d H:i:s',time()),
									'nns_action' => 'add',
									'nns_status' => 0,
									'nns_name' => "[{$stock['data_info']['vod_name']}][{$line_arr[2]}]",
									'nns_op_mtime' => round(np_millisecond_f()*1000),
									'nns_release_time' => $relase_time,
							);
							nl_op_queue::add($dc, $op_add_params);
							//$queue_task_model->q_add_task($stock['data_info'], 'video', 'add',$sp['nns_id'],null,false,'',null,0,'',$config);
						}
					}
					//
					break;
				case 'c2_import'://加入C2队列
					foreach ($sp_info as $sp)
					{
						//检查C2队列是否存在
						$check_c2 = nl_c2_task::query_c2_exsist($dc, 'index', $stock['data_info']['index_id'], $sp['nns_id']);
						if($check_c2['ret'] != '0')
						{
							continue;
						}
						if(!is_array($check_c2['data_info']) || empty($check_c2['data_info']))//不存在则添加
						{
							$c2_add_params = array(
									'nns_type' => 'index',
									'nns_ref_id' => $stock['data_info']['index_id'],
									'nns_src_id' => $stock['data_info']['vod_id'],
									'nns_org_id' => $sp['nns_id'],
									'nns_cp_id' => $source_id,
									'nns_create_time' => date('Y-m-d H:i:s',time()),
									'nns_action' => 'add',
									'nns_status' => 1,
									'nns_name' => "[{$stock['data_info']['vod_name']}][{$line_arr[2]}]",
							);
							nl_c2_task::add($dc, $c2_add_params);
						}
						else //存在则把状态置为初始状态
						{
							$edit_params = array(
									'nns_action' => 'add',
									'nns_status' => 1,
									'nns_epg_status' => 97,
                                    'nns_ref_id' => $stock['data_info']['index_id'],
                                    'nns_src_id' => $stock['data_info']['vod_id'],
							);
							nl_c2_task::edit($dc, $edit_params, $check_c2['data_info'][0]['nns_id']);
						}
					}
					break;
			}
		}
	}
	fclose($upload_file);
}

/**
 * 片源从CSV导入
 * @param object $dc
 * @param string $upload_file 上传文件
 * @param string $source_id 上游来源信息
 * @param string $queue_name 导入队列名
 * @param array $sp_info
 */
function stock_media_import_by_csv($dc,$upload_file,$source_id,$queue_name,$sp_info)
{
	$upload_file = fopen($upload_file, 'r');
	$num = 0;
	$first = false;
	$flag = true;
	//$queue_task_model = new queue_task_model();
	while (!feof($upload_file))
	{
		$line_arr = fgetcsv($upload_file);
		if($first === false)
		{
			unset($first);
			continue;
		}
		if (is_array($line_arr) && !empty($line_arr))
		{
			$kbps = empty($line_arr[9]) ? 0 : $line_arr[9];
			$asset_import_id = $line_arr[0];//主媒资ID
			$index_import_id = $line_arr[1];//分集ID
			//整理vod_index
			$vod_media_info = array(
					'nns_import_id' => $line_arr[2],
					'nns_name' => $line_arr[3],
					'nns_file_time_len' => $line_arr[4],//导入单位为秒
					'nns_filetype' => empty($line_arr[5]) ? 'ts' : $line_arr[5],
					'nns_url' => $line_arr[6],
					'nns_mode' => strtolower($line_arr[7]),
					'nns_file_size' => empty($line_arr[8]) ? 1 : $line_arr[8],
					'nns_kbps' => $kbps,
					'nns_action' => 'add',
					'nns_cp_id' => $source_id,
                    'nns_ext_url' => isset($line_arr[10]) ? $line_arr[10] : '',
                    'nns_content_id' => isset($line_arr[11]) ? $line_arr[11] : '',
			);
			$stock = nl_stock_import::stock_media_import($dc, $vod_media_info,$asset_import_id, $index_import_id,$source_id);//导入媒资
			if($stock['ret'] != 0 || empty($queue_name) || empty($sp_info))
			{
				continue;
			}
			//$stock返回的是主媒资GUID+分集的GUID array('vod_id','vod_name','index_id','index_name','media_id')
			switch ($queue_name)
			{
				case 'core_import'://加入中心同步队列
					foreach ($sp_info as $sp)
					{
						//检查中心同步队列是否存在
						$check_params = array(
								'nns_type' => 'media',
								'nns_video_id' => $stock['data_info']['vod_id'],
								'nns_index_id' => $stock['data_info']['index_id'],
								'nns_media_id' => $stock['data_info']['media_id'],
								'nns_org_id' => $sp['nns_id'],
								'nns_cp_id' => $source_id
						);
						$check_op_queue = nl_op_queue::get_overtime_op_queue_by_condition($dc, $check_params);
						if($check_op_queue['ret'] != '0')
						{
							continue;
						}
						//$config = json_decode($sp['nns_config'],true);
						if(!is_array($check_op_queue['data_info']) || empty($check_op_queue['data_info']))//不存在则添加，存在则忽略
						{
                            //获取下游注入配置
                            $sp_config = json_decode($sp['nns_config'],true);
                            $op_status = 0;
                            if((int)$sp_config['disabled_clip'] !== 2 && (int)$sp_config['disabled_clip'] !== 3)
                            {
                                $op_status = 2;
                            }
							$op_add_params = array(
									'nns_type' => 'media',
									'nns_video_id' => $stock['data_info']['vod_id'],
									'nns_index_id' => $stock['data_info']['index_id'],
									'nns_media_id' => $stock['data_info']['media_id'],
									'nns_org_id' => $sp['nns_id'],
									'nns_cp_id' => $source_id,
									'nns_create_time' => date('Y-m-d H:i:s',time()),
									'nns_action' => 'add',
									'nns_status' => $op_status,
									'nns_name' => "[{$stock['data_info']['vod_name']}][{$stock['data_info']['index_name']}][{$line_arr[3]}][{$kbps}/kbps]".strtolower($line_arr[7]),
									'nns_op_mtime' => round(np_millisecond_f()*1000),
									'nns_release_time' => date('Y-m-d',time()),
							);
							nl_op_queue::add($dc, $op_add_params);
							//$queue_task_model->q_add_task($stock['data_info'], 'video', 'add',$sp['nns_id'],null,false,'',null,0,'',$config);
						}
					}
					//
					break;
				case 'c2_import'://加入C2队列
					foreach ($sp_info as $sp)
					{
						//检查C2队列是否存在
						$check_c2 = nl_c2_task::query_c2_exsist($dc, 'media', $stock['data_info']['media_id'], $sp['nns_id']);
						if($check_c2['ret'] != '0')
						{
							continue;
						}
						if(!is_array($check_c2['data_info']) || empty($check_c2['data_info']))//不存在则添加
						{
							$c2_add_params = array(
									'nns_type' => 'media',
									'nns_ref_id' => $stock['data_info']['media_id'],
									'nns_src_id' => $stock['data_info']['index_id'],
                                    'nns_file_path' => $line_arr[6],
									'nns_org_id' => $sp['nns_id'],
									'nns_cp_id' => $source_id,
									'nns_create_time' => date('Y-m-d H:i:s',time()),
									'nns_action' => 'add',
									'nns_status' => 1,
									'nns_name' => "[{$stock['data_info']['vod_name']}][{$stock['data_info']['index_name']}][{$line_arr[3]}][{$kbps}/kbps]".strtolower($line_arr[7]),
							);
							nl_c2_task::add($dc, $c2_add_params);
						}
						else //存在则把状态置为初始状态
						{
							$edit_params = array(
									'nns_action' => 'add',
									'nns_status' => 1,
									'nns_epg_status' => 97,
                                    'nns_ref_id' => $stock['data_info']['media_id'],
                                    'nns_src_id' => $stock['data_info']['index_id'],
							);
							nl_c2_task::edit($dc, $edit_params, $check_c2['data_info'][0]['nns_id']);
						}
					}
					break;
			}
		}
	}
	fclose($upload_file);
}
/**
 * 反馈信息
 * @param $code
 * @param $msg
 */
function return_csv_msg($code,$msg)
{
	$array = array(
			'ret' => $code,
			'info'=> $msg,
	);
	return json_encode($array);
}
